/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.robotplayground.gui.running;

import net.zarubsys.robotplayground.core.program.API;
import net.zarubsys.robotplayground.core.session.RunningSession;
import net.zarubsys.robotplayground.gui.running.logging.SessionConsole;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.internal.console.ConsoleView;

/**
 * StopCommandHandler
 *
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
@SuppressWarnings("restriction") // need access to console view to be able to find selected console
public class StopCommandHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IConsole console = getConsole(event);
		if (!(console instanceof SessionConsole)) return null; // executed on non-compatible console = nothing to do
		SessionConsole sessionConsole = (SessionConsole) console;
		stopSession(sessionConsole.getRunningSession());
		return null;
	}

	private void stopSession(RunningSession runningSession) {
		API api = runningSession.getApi();
		api.getEnvironment().stop(api, "Terminated manually.");
	}

	private IConsole getConsole(ExecutionEvent event) {
		IWorkbenchPart part = getPart(event);
		Assert.isLegal(part instanceof ConsoleView, "Expecting console view!!!");
		ConsoleView consoleView = (ConsoleView) part;
		IConsole console = consoleView.getConsole();
		return console;
	}

	private IWorkbenchPart getPart(ExecutionEvent event) {
		IWorkbenchSite site = HandlerUtil.getActiveSite(event);
		IWorkbenchPage page = site.getPage();
		IWorkbenchPart part = page.getActivePart();
		return part;
	}

}

